package com.duobaoyu.dby.supply.biz.strategy.order;

import com.duobaoyu.dby.channel.adapter.enums.ChannelCodeEnum;
import com.duobaoyu.dby.supply.biz.client.boundary.order.bean.bo.OrderInfoBO;
import com.duobaoyu.dby.supply.biz.producer.SupplyChainMQProducer;
import com.duobaoyu.dby.supply.biz.strategy.AbstractSyncOrderStatusStrategy;
import com.duobaoyu.dby.supply.common.biz.bo.order.ChannelOrderDetailOutBO;
import com.google.common.collect.Sets;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * ChengYang同步订单状态
 * @Author yangyong
 * @Date 2023/11/17
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ChengYangSyncOrderStatusStrategy extends AbstractSyncOrderStatusStrategy{
	private final SupplyChainMQProducer supplyChainMQProducer;

	@Override
	protected Set<String> channelCodes(){
		return Sets.newHashSet(ChannelCodeEnum.CHENG_YANG.getValue());
	}

	@Override
	protected Boolean beforeCheckParams(OrderInfoBO orderInfo){
		return StringUtils.isNotBlank(orderInfo.getOrderTradeSn());
	}

	@Override
	protected Object afterHandler(OrderInfoBO orderInfo, ChannelOrderDetailOutBO channelOrderDetail){
		if(Objects.isNull(channelOrderDetail)){
			log.warn("ChengYang同步订单状态无订单信息");
			return null;
		}
		List<ChannelOrderDetailOutBO.VirtualOrderDetail> virtualOrderDetailList = channelOrderDetail.getVirtualOrderDetailList();
		if(CollectionUtils.isEmpty(virtualOrderDetailList)){
			log.warn("ChengYang同步订单状态无订单明细");
			return null;
		}
		ChannelOrderDetailOutBO.VirtualOrderDetail virtualOrderDetail = virtualOrderDetailList.stream()
				.filter(o -> Objects.equals(o.getChannelOrderSn(),orderInfo.getChannelOrderSn()))
				.findFirst().orElse(null);
		if(Objects.isNull(virtualOrderDetail)){
			log.warn("ChengYang同步订单状态无匹配的渠道单");
			return null;
		}
		log.info("ChengYang同步订单状态供应链三方交易单号:{},渠道子单号:{},订单状态:{},渠道单状态:{}", orderInfo.getOrderTradeSn(), orderInfo.getChannelOrderSn(),
				orderInfo.getOrderStatus(), virtualOrderDetail.getStatus());
		if(Objects.equals(orderInfo.getOrderStatus(), virtualOrderDetail.getStatus())){
			log.info("ChengYang同步订单状态无需同步");
			return null;
		}
		boolean updateFlag = modifyOrderStatus(orderInfo, virtualOrderDetail.getStatus());
		if(updateFlag){
			supplyChainMQProducer.orderAlterSend(orderInfo.getSupplyTradeSn(), orderInfo.getServerName());
		}
		return updateFlag;
	}
}
